<template>
	<view class="container">
		<!-- <titlebar mode="" :back="true" ></titlebar> -->
		<!-- <view class="logo">
			<image class="logo_image" src="/static/images/common/login_logo_image@2x.png"></image>
			<view class="logo_welcome">欢迎进入LEVC的世界</view>
		</view> -->
		<view class="logo_new">
			<image class="logo_image_new"
				src="@appstatic/user/user_icon_toplogo.png"></image>
		</view>
		<view style="padding-left: 40.5px; padding-top: 25.73px;padding-bottom: 54px;">
			<text style="font-weight: 300;font-size: 24px;line-height: 34px;">
				欢迎加入派方
			</text>
		</view>
		<view class="content">
			<!-- 登录表单 -->
			<view class="login-form">
				<view class="row">
					<!-- <view class="area_code">+86 |</view> -->
					<image style="width: 10.67px;height: 14px;padding-left: 19px;padding-right: 11px;"
						src="@appstatic/user/user_icon_mobile.png" mode="aspectFit">
					</image>
					<input type="number" maxlength="11" class="login-form-input" :value="mobile"
						placeholder="手机号" @input="mobileInput" placeholder-class="phcolor">
					</input>
				</view>
				<view class="input_space_margin_top_40" style="margin-top: 40px; "></view>
				<view class="row">
					<image style="width: 12px;height: 14.67px;padding-left: 19px;padding-right: 11px;"
						src="@appstatic/user/user_icon_code.png" mode="aspectFit">
					</image>
					<input type="number" maxlength="6" class="login-form-input shortinput" :focus="false"
						:value="verificationCode" placeholder="验证码" @input="verificationCodeInput"
						placeholder-class="ph_msgcolor">
					</input>
					<CountDownView id="countView" ref="countView" @countStartEvent="countStartEvent"
						@countEndEvent="countEndEvent" mode="newLogin"></CountDownView>
				</view>

				<view v-if="errormessage.length!=0" class="row footOpration">
					<view style="color:#d6253f;">{{errormessage}}</view>
				</view>
			</view>


			<!-- 登录按钮 -->
			<!-- <view class="input_space_margin_top_50" style="margin-top: 50px; "> </view> -->
			<view>
				<button class="login-button" @click="completeTouched" hover-class="btn-style-hover" plain="true">
					登录
				</button>
			</view>
		</view>
		<view style="display: flex;flex-direction: column;justify-content: space-between;height: calc(100vh - 647px);">
			<view class="jurisdiction" >
				
					<checkbox-group @change="onCheckChange">
						<view class="check" >
						<checkbox value="vvv" :checked="checked" color="#BDBDBD" style="transform: scale(0.46);"></checkbox>
						</view>
					</checkbox-group>
				
				<view class="checkbox-test">
					我已阅读并同意方机车
				</view>
				<view class="text" @click="agreementTouched" style="color: #EA5404;">
					《用户服务协议》
				</view>
				<view class="checkbox-test">、</view>
				<view class="text" @click="privateTouched" style="color: #EA5404;">
					《隐私政策》
				</view>
			</view>
			<view class="wechat" v-if="env=='dev'|| env=='test'" style="display: flex;justify-content: center;height: 48px;margin-top: 10px;">
				<image @click="wxloginTouched" style="width: 42px;height: 42px;"
					src="@appstatic/user/user_icon_wechat.png" mode=""></image>
			</view>
		</view>

	</view>
</template>

<script>
	var app = getApp();
	const network = require("@manager/network-manager.js");
	const dialog = require("@utils/dialog.js");
	import CountDownView from "@components/CountDownView/CountDownView.vue";
	import util from '@utils/util';
	import JSEncrypt from '@utils/jsencrypt';

	export default {
		data() {
			return {
				checked: false,
				mobile: '',
				password: '',
				passwordPlaceholder: '',
				verificationCode: '',
				//短信验证码
				errormessage: '',
				mode: '',
				code: '',
				from: '',
				graphicVerificationCode: "",
				timer: 60,
				uuid: '',
				system: '', // 系统版本
				platform: '', // 平台
				env:app.globalData.config.env
			};
		},

		components: {
			// vanCheckbox,
			CountDownView
		},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			var that = this;
			if (options && options.from) {
				this.from = options.from;
			}

			// 先判断 系统版本
			uni.getSystemInfo({
				success: (res) => {
					this.system = res.system
					this.platform = res.platform

					console.log(JSON.stringify(res));
				},
				fail: (err) => {},
				complete: () => {}
			})
			this.getPublicKey();

		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			// app.trackPage(util.getNavigationBarTitle());

		},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {},
		methods: {
			getPublicKey: function(uuid) {
				this.uuid = (Math.random() * 1000) | 0;

				var that = this;
				var uri = app.globalData.config.interfaces.URL_COMMON_PUBLIC_KEY;
				var params = {
					"id": this.uuid
				};
				const header = {}; //
				network.get(uri, params, "form", header).then(res => {

					if (res.code == 200) {
						that.rasKey = res.data;

						that.encrypt(that.rasKey, "xxxx");
					}
				}).catch(res => {});
			},
			encrypt: function(key, msg) {
				const jsencrypt = new JSEncrypt()
				jsencrypt.setPublicKey(key)

				return jsencrypt.encrypt(msg)
			},
			//获取用户输入的用户名
			mobileInput: function(e) {
				this.mobile = e.detail.value

			},
			//获取用户输入的密码
			passwordInput: function(e) {
				this.password = e.detail.value

			},
			//获取用户输入的图形
			graphicVerificationCodeInput: function(e) {
				this.graphicVerificationCode = e.detail.value

			},
			//获取用户输入的验证码
			verificationCodeInput: function(e) {

				this.verificationCode = e.detail.value

			},
			//手机验证码
			countStartEvent: function() {
				var that = this;
				console.log('===================')
				if (that.mobile.length == 0) {
					dialog.toast("手机号不能为空");
					return;
				}

				if (that.mobile.length != 11) {
					dialog.toast("手机号格式有误");
					return;
				} //计时
				that.$refs.countView.startCount();
				var uri = app.globalData.config.interfaces.URL_SYS_SENDSMS;
				var params = {
					"phone": that.mobile
				};
				const header = {}; //
				network.post(uri, params, "form", header).then(res => {
					if (res.code == 200) {
						var result = res.data;
						that.code = result

					} else {
						that.$refs.countView.stopCount();
						if (res.message) {
							dialog.toast(res.message);
						} else {
							dialog.toast('验证码发送失败');
						}
					}
				}).catch(res => {});
				console.log("countStartEvent");
			},
			countEndEvent: function() {
				console.log("countEndEvent");
			},
			validate: function() {
				var that = this;

				if (that.mobile.length == 0) {
					return "手机号不能为空";
				}

				if (that.mobile.length != 11) {
					return "手机号格式有误";
				}

				if (that.verificationCode.length == 0) {
					return "验证码不能为空";
				}

				return null;
			},
			//完成
			completeTouched: function() {

				if (!this.checked) {
					dialog.toast("请查看并同意协议后继续");
					return;
				}

				var that = this;
				var error = that.validate();

				if (error) {
					dialog.toast(error);
					return;
				}
				
				var loginType = "";
				if(app.globalData.systemPlatform=="WEIXIN"){
					loginType = "0"
				}else if (app.globalData.systemPlatform=="App"){
					loginType = "1"
				}
				var loginDevice = ""
				if(app.globalData.systemVersionNum.indexOf("Android") != -1){
					loginDevice = "0"
				}
				
				if(app.globalData.systemVersionNum.indexOf("iOS") != -1){
					loginDevice = "1"
				}
				
				
				var uri = app.globalData.config.interfaces.URL_SYS_LOGIN; //(value = "渠道(1.注册；2.试驾；3.活动报名)")
				// "来源(1.pc；2.移动端；3.小程序；4.app）")
				// 

				var params = {
					"code": that.verificationCode,
					"ditch": 1,
					"isfrom": 4,
					"phone": that.mobile,
					"loginType": loginType,//登录来源(0 小程序 1 用户app 2 渠道端 3 pc)
					"loginDevice": loginDevice,//登录设备(0 Android 1 IOS)
					"loginVersion":uni.getStorageSync("version")
				};
				const header = {};
				var that = this;

				network.post(uri, params, "json", header).then(res => {

					if (res.code == 200) {
						app.saveToken(res.data.token);
						//登录成功没返回用户信息 接口再次获取下
						that.getUserWithMobile(that.mobile);
					} else {
						dialog.toast(res.message);
					}
				}).catch(err => {
					console.log(err)
				});
			},
			//获取用户信息
			getUserWithMobile: function(mobile) {
				// debugger
				var params = {
					"phone": mobile
				};
				const header = {};
				var that = this;
				network.get(app.globalData.config.interfaces.URL_SYS_LOAD_USERINFO, params, "form", header).then(
					res => {
						// debugger
						if (res.code == 200) {
							app.saveUser(res.data);
							// this.$fire.$emit("loginSuccess");
							// uni.setStorageSync("loginSuccess", "loginSuccess");
							// uni.navigateBack({
							// 	changed: true
							// }); //返回上一页
							//登录成功后返回来源页面
							util.goBackSourcePage(this.from);
						} else {
							dialog.toast("登录失败");
						}
					}).catch(res => {
					dialog.toast(res.errMsg);
					console.error(res);
				});
			},

			onCheckChange: function(e) {
				this.checked = e.detail.value.length > 0;

			},
			agreementTouched: function(e) {
				uni.navigateTo({
					url: '/pages/user/agreement'
				});
			},
			privateTouched: function(e) {
				uni.navigateTo({
					url: '/pages/user/private'
				});
			},


			//获取用户信息 检验注册没注册
			checkWXUser: function(openId, unionId) {
				var loginType = "";
				if(app.globalData.systemPlatform=="WEIXIN"){
					loginType = "0"
				}else if (app.globalData.systemPlatform=="App"){
					loginType = "1"
				}
				var loginDevice = ""
				if(app.globalData.systemVersionNum.indexOf("Android") != -1){
					loginDevice = "0"
				}
				
				if(app.globalData.systemVersionNum.indexOf("iOS") != -1){
					loginDevice = "1"
				}
				
				
				
				var params = {
					"openid": this.encrypt(this.rasKey, openId),
					"unionId": this.encrypt(this.rasKey, unionId),
					"id": this.uuid,
					
					"loginType": loginType,//登录来源(0 小程序 1 用户app 2 渠道端 3 pc)
					"loginDevice": loginDevice,//登录设备(0 Android 1 IOS)
					"loginVersion":uni.getStorageSync("version")
				};
				const header = {};
				var that = this;
				return new Promise((resolve, reject) => {
					network.get(app.globalData.config.interfaces.URL_SYS_LOAD_OPENID, params, "form", header)
						.then(res => {
							if (res.code == 200) {
								if (res.data != null && res.data.id) {
									console.log("已注册");
									resolve(res.data);
								} else {
									console.log("未注册");
									reject(true);
								}
							} else {
								reject(false);
							}
						}).catch(res => {
							reject(false);
						});
				});
			},
			 // 微信如果未注册   去 完善信息页面注册
			bindMobile: function(userInfo, isApple) {
				console.log("bindMobile");
				uni.navigateTo({
					url: '/pages/user/register?isweixin=1&from=&wxinfo=' + JSON.stringify(userInfo),
					fail(err) {
						console.log(err, 'err')
					}
				});
			},

			//通过微信登录
			wxloginTouched: function(e) {

				if (!this.checked) {
					dialog.toast("请查看并同意协议后继续");
					return;
				} // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
				// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
				var that = this;
				
				if (plus.runtime.isApplicationExist({ pname: 'com.tencent.mm', action: 'weixin://' })) {
					uni.showLoading();
				} else {
					console.log("未安装微信");
					// 未安装微信会跳转到短信登录 需要隐藏loading
				}
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						//支持微信、qq和微博等
						console.log('-------获取getProvider -----res' + JSON.stringify(res));

						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									// this.$fire.$emit("loginSuccess");
									// uni.setStorageSync("loginSuccess", "loginSuccess");
									let access_token = loginRes.authResult.access_token
									let openid = loginRes.authResult.openid;
									let unionid = loginRes.authResult.unionid

									console.log('-------获取openid(unionid)-----');
									console.log('token', access_token)
									console.log('unionid', unionid)
									console.log(JSON.stringify(loginRes));
									// 获取用户信息
									uni.getUserProfile({
										provider: 'weixin',
										lang: 'zh_CN',
										success: function(infoRes) {
											console.log('-------获取微信用户所有-----' +
												JSON.stringify(infoRes
													.userInfo));
											uni.hideLoading();

											//检查用户是否存在 存在直接返回，不存在绑定手机号注册
											that.checkWXUser(openid, unionid).then(
												respone => {
													//保存用户信息
													app.saveUser(
														respone);
													app.saveToken(
														respone.token);
													uni.navigateBack({
														delta: 1
													});
												}).catch(noerr => {
												if (noerr) {
													that.bindMobile(infoRes
														.userInfo,
														false);
												} else {
													that.getPublicKey();
													dialog.toast("微信登录失败");
												}
											});

										},
										fail: function(error) {
											uni.hideLoading();
											dialog.toast("获取微信用户信息失败");
											console.log('-------获取getUserInfo' + JSON.stringify(error));
										}
									});
								},
								fail: function(error) {
									uni.hideLoading();
									dialog.toast("微信登录失败");
									console.log('-------获取openifail' + JSON.stringify(error));
								}
							});
						} else {
							uni.hideLoading();
							dialog.toast("微信登录失败");
						}
					}
				});


			},
			  
		}
	};
</script>
<style>
	/* pages/user/register/register.wxss */

	.container {
		/* background: url("https://levcdmposs.oss-cn-hangzhou.aliyuncs.com/miniapp/images/news_head1.png") center no-repeat; */
		background: url("@appstatic/user/user_icon_bottomlogo.png") bottom right no-repeat;
		background-size: 323px, 287px;
		width: 100vw;
		height: 100vh;
		/* height: calc(100vh - 44px); */
		/* display: flex;
		flex-direction: column; */
	}

	.content {
		/* padding: 51rpx; */
		/* padding-top: 80px; */
		/* padding-left: 24px;
		padding-right: 24px; */
		display: flex;
		flex-direction: column;
		padding-left:20px;
		padding-right:20px
	}

	.row {
		display: flex;
		flex-direction: row;
		align-items: center;
		border-bottom: 1px solid #ECEDEE;
		height: 42px;
		/* width: 327px; */
		margin: auto;
		/* height: 90rpx; */
		/* margin-top: 40rpx;
		margin-right: 30rpx;
		margin-left: 30rpx; */

	}

	.logo_new {
		display: flex;
		justify-content: center;
		flex-direction: column;

		/* top: 56px; */
		/* background: linear-gradient(180.02deg, #f7f8fa 0.01%, #ffffff 95.39%); */
	}

	.logo_image_new {
		width: 72px;
		height: 86.33px;
		margin-left: 40px;
		margin-top: 40px;
	}

	.login-form-input {
		font-size: 28rpx;
		color: #4F4F4F;
		height: 40rpx;
		line-height: 40rpx;
		padding-left: 0rpx;

		width: 100%;
	}

	.shortinput {
		width: calc(100% - 20rpx - 173rpx)
	}

	.canvas {
		width: 85px;
		background-color: #f7faff;
	}

	.login-image {
		width: 100%;
		height: 420rpx;
	}

	.login-image>image {
		margin-left: calc((100% - 353rpx) / 2);
		margin-top: 85rpx;
		width: 353rpx;
		height: 238rpx;
	}

	.login-button {
		line-height: 80rpx;
		height: 42px;
		
		/* position: absolute; */
		margin: auto;
		border: none;
		/* left:calc((100% - 600rpx) / 2); */
		background-color: #FFD700;
		border-radius: 2px;
		font-size: 16px;
		font-weight: 400;
		color: #333333;
		margin-top: 56px;
		/* bottom: 100rpx; */
	}

	.logo_mode {
		width: 40px;
		height: 40px;
		margin: 10px;
	}



	/* //原生的按钮就是这样难改 */
	button.login-button[plain] {
		border: 0;
		background-color: #EA5404;
		color: #ffffff;
		/* font-weight: bold; */
		font-size: 16px;
		font-weight: 400;
	}


	.footOpration {
		border-bottom: 0px;
		height: 75rpx;
		margin-top: 0rpx;
		font-size: 26rpx;
		display: flex;
		justify-content: space-between;
	}

	.logo {
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
	}

	.logo_image {
		height: 100rpx;
		width: 282rpx;
		margin-top: 152rpx;
	}

	.logo_welcome {
		color: #333333;
		font-size: 36rpx;
		margin-top: 40rpx;
		margin-bottom: 40rpx;
	}

	.area_code {
		color: #333333;
		font-size: 28rpx;
		width: 20%;
	}

	.phcolor {
		color: #BDBDBD;
		font-size: 16px;
		font-weight: 400;
	}

	.ph_msgcolor {
		color: #BDBDBD;
		font-size: 16px;
		font-weight: 400;
	}

	.jurisdiction {
		left: 100rpx;
		display: flex;
		align-items: center;
		flex-direction: row;
		justify-content: center;
		font-size: 10px;
		margin-top: 20px;

	}

	.checkbox-test {
		font-size: 12px;
		color: #BDBDBD;
	}

	.text {
		font-size: 12px;
	}

	.buttom-logo {
		height: 287px;
		width: 323px;
		left: 52px;

	}
	
	.check {
		width:40px;
		height:40px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>
